package com.example.adminframework.controller;


import com.example.adminframework.common.exception.NodeException;
import com.example.adminframework.common.redis.Redis;
import com.example.adminframework.constant.ErrorCode;
import com.example.adminframework.constant.HttpCode;
import com.example.adminframework.model.bo.NodeBO;
import com.example.adminframework.response.ResultContent;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@RestController
@Api(tags = "短信相关操作")
@RequestMapping(value = "/note")
public class NodeController {

    @Resource
    private Redis redis;

    @PostMapping("/send")
    @ApiOperation("发送验证码")
    public ResultContent send(@RequestBody NodeBO nodeBO) {
        String randomCode = getRandomCode();
        if (nodeBO.getCode() == 0){
            throw new NodeException(HttpCode.BAD_REQUEST, ErrorCode.ANALYSIS_SCRIPT_RELEVANCE_ERROR);
        }
        redis.setStrValue(nodeBO.getPhone(),randomCode,10, TimeUnit.MINUTES);
        return ResultContent.success(new NodeBO(nodeBO.getPhone(),Long.valueOf(randomCode)));
    }



    private String getRandomCode(){
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            int index = random.nextInt(9);
            sb.append(""+index);
        }
        return sb.toString();
    }
}
